﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Xml;
using System.Xml.Xsl;
using System.Xml.Linq;
using System.Linq;
using System.Diagnostics;

namespace MyPublisher.Composition.Fop
{
    [Transform(
    Name = "DOTNET.Html2Dita",
    Provider = "DOTNET",
    InputType = FragmentType.HTML,
    OutputType = FragmentType.DITA)]
    public class Html2Dita : ITransform
    {
        #region ITransform Members

        public void Tranform(Fragments inputs, Fragment output)
        {
            Fragment htmlFragment = inputs.GetFragment<Fragment>(FragmentType.HTML);
            Fragment ditaFragment = output;
            string htmlfile = htmlFragment.Path;
            string ditafile = ditaFragment.Path;

            if (!File.Exists(htmlfile))
            {
                throw new TransformException(string.Format("Input htmlfile -{0}- is not existent.", htmlfile));
            }

            PreprocessHtmlFile(htmlfile);
            DoXslTransform(htmlfile, ditafile);
            PostProcess(output);
        }

        private static void PreprocessHtmlFile(string htmlfile)
        {
            HtmlTidy.Tidy(htmlfile);
            try
            {
                XDocument doc = XDocument.Load(htmlfile);
            }
            catch (Exception e)
            {
                string err = string.Format("Input htmlfile -{0}- is invalid.", htmlfile);
                throw new TransformException(err, e);
            }
        }

        private void DoXslTransform(string htmlfile, string ditafile)
        {
            try
            {
                using (Stream stream = GetType().Assembly.GetManifestResourceStream("MyPublisher.Composition.Fop.h2d.xsl"))
                using (XmlReader reader = new XmlTextReader(stream))
                {
                    XslCompiledTransform transform = new XslCompiledTransform();
                    transform.Load(reader);
                    transform.Transform(htmlfile, ditafile);
                }
            }
            catch (Exception e)
            {
                throw new TransformException("Failed to transform.", e);
            }
        }

        private static void PostProcess(Fragment output)
        {
            XDocument document = XDocument.Load(output.Path);
            //<!DOCTYPE concept PUBLIC "-//OASIS//DTD DITA Concept//EN" "../../dtd/concept.dtd">
            string name = document.Root.Name.LocalName;
            document.Root.AddBeforeSelf(
                new XDocumentType(name, "-//OASIS//DTD DITA Concept//EN", "../../dtd/topic.dtd", null));

            //remove comment nodes
            List<XNode> commentNodes = new List<XNode>();
            foreach (XNode node in document.DescendantNodes())
            {
                if (node.GetType() == typeof(XComment))
                {
                    commentNodes.Add(node);
                }
            }

            foreach (XNode node in commentNodes)
            {
                node.Remove();
            }

            //normalize dita
            List<XElement> subsections = new List<XElement>();
            XElement body = document.Root.Element("body");
            foreach (XElement section in body.Elements("section"))
            {
                foreach (XElement subsection in section.Elements("section"))
                {
                    MoveSectionElements(section, subsection);
                    subsections.Add(subsection);
                }
            }
            foreach (XElement section in subsections)
            {
                section.Remove();
            }

            //remove empty nodes

            document.Save(output.Path);
        }

        private static void MoveSectionElements(XElement rootsection,XElement section)
        {
            foreach (XElement element in section.Elements())
            {
                if (element.Name == "section")
                {
                    MoveSectionElements(rootsection, element);
                }
                else
                {
                    if (rootsection != section)
                    {
                        rootsection.Add(element);
                    }
                }
            }
        }

        #endregion
    }
}
